package com.cicadamob.contact.api.Utils;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Locale;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapCommonUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.bitmap.callback.DefaultBitmapLoadCallBack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Base64;
import android.widget.ImageView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class ImageUtil {
	// private static BitmapUtils bitmapUtils;

	/**
	 * 图片的裁剪
	 * 
	 * @param uri
	 */
	public static void startPhotoZoom(Context context, Uri uri,
			int requestCode, int width, int height) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("aspectX", 1);// 裁剪宽高比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", width);// 裁剪宽高
		intent.putExtra("outputY", height);
		intent.putExtra("return-data", true);
		// startActivityForResult(intent, SHOW_REQUEST_CODE);
		((Activity) context).startActivityForResult(intent, requestCode);
	}

	/**
	 * 保存裁剪后的图片
	 */
	public static boolean getImageToView(Context context, Intent data,
			ImageView imageView, String tempPath) {
		Bundle extras = data.getExtras();
		Bitmap photo = null;
		boolean suc = false;
		if (extras != null) {
			photo = extras.getParcelable("data");
			if (photo != null) {
				FileOutputStream out = null;
				try {
					out = new FileOutputStream(tempPath);
					photo.compress(CompressFormat.JPEG, 60, out);
					out.flush();
					out.close();
					suc = true;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				photo = toRoundCorner(photo, 20);
				Drawable drawable = new BitmapDrawable(photo);
				// imageView.setBackgroundDrawable(drawable);
				imageView.setImageDrawable(drawable);
			} else {
				ToastShow(context, "图片处理异常");
			}

		}
		return suc;
	}

	/**
	 * 图片圆角 FIXME
	 * 
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}




	/**
	 * String转Bitmap
	 * 
	 * @param str
	 * @return
	 */
	public static Bitmap convertStringToIcon(String str) {
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(str, android.util.Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
			return bitmap;
		} catch (Exception e) {

			return null;
		}

	}

	/**
	 * 计算图片的缩放值
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	// 计算图片原始大小
	public static int SampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		// 上下限范围
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}

	}

	// 根据原始图片大小进行缩放
	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = SampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8;
		}

		return roundedSize;
	}
	
//	@SuppressLint("SdCardPath")
//	public static String getSmallBitmap(String filePath) {
//		
//		if(filePath==null||filePath.length()==0)
//			return null;
//		
//		final BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(filePath, options);
//		// Calculate inSampleSize
////		options.inSampleSize = calculateInSampleSize(options, 1080, 720);
//		// Decode bitmap with inSampleSize set
//		options.inSampleSize = computeSampleSize(options,  -1,1080*720);   
//
//		options.inJustDecodeBounds = false;
//		Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
//		FileOutputStream fos = null;
//		String tempTaskPath = "/sdcard/ManagerAssistant/TaskPic/";
//		String name = DateFormat.format("yyyyMMdd_hhmmss",
//				Calendar.getInstance(Locale.CHINA))
//				+ ".jpg";
//		try {
//			File file = new File("tempTaskPath");
//			file.mkdirs();// 创建文件夹
//			String fileName = "/sdcard/ManagerAssistant/TaskPic/" + name;
//			fos = new FileOutputStream(fileName);
//			bmp.compress(Bitmap.CompressFormat.JPEG, 40, fos);
//			fos.flush();
//			fos.close();
//			if (!bmp.isRecycled()) {
//				bmp.recycle();
//			}
//			return fileName;
//			//return file.getAbsolutePath();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		if (!bmp.isRecycled()) {
//			bmp.recycle();
//		}
//		return null;
//	}

	/**
	 * 根据路径获得图片并压缩，返回bitmap用于显示
	 * 
	 * @param filePath
	 *            原始图片路径
	 * @param newfilePath
	 *            生成新图片的保存文件夹
	 * @return 生成新图片的文件名称（包含路径）
	 */
	@SuppressLint("SdCardPath")
	public static String getsmallBitmap(String filePath, String newfilePath) {
		if (filePath == null || filePath.length() == 0)
			return null;

		FileDescriptor fd;
		try {
			fd = new FileInputStream(filePath).getFD();

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			// BitmapFactory.decodeFile(imgFile, options);
			BitmapFactory.decodeFileDescriptor(fd, null, options);

			// FileInputStream fis = new FileInputStream(filePath);
			// BitmapFactory.decodeStream(fis);
			options.inSampleSize = computeSampleSize(options, -1, 1080 * 720);
			try {
				// 这里一定要将其设置回false，因为之前我们将其设置成了true
				// 设置inJustDecodeBounds为true后，decodeFile并不分配空间，即，BitmapFactory解码出来的Bitmap为Null,但可计算出原始图片的长度和宽度
				options.inJustDecodeBounds = false;
				Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

				FileOutputStream fos = null;
				// String tempTaskPath = "/sdcard/ManagerAssistant/TaskPic/";
				String name = DateFormat.format("yyyyMMdd_hhmmss",
						Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				try {
					File file = new File(newfilePath);
					file.mkdirs();// 创建文件夹
					String fileName = newfilePath + name;
					fos = new FileOutputStream(fileName);
					bmp.compress(Bitmap.CompressFormat.JPEG, 40, fos);
					fos.flush();
					fos.close();
					if (!bmp.isRecycled()) {
						bmp.recycle();
					}
					return fileName;
					// return file.getAbsolutePath();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (!bmp.isRecycled()) {
					bmp.recycle();
				}
				return null;
			} catch (OutOfMemoryError err) {
				return null;
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

	}

	private static void ToastShow(Context context, String text) {
		// TODO Auto-generated method stub
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	 /**
	  * 显示网络图片
	  * @param url
	  * @param context
	  * @param imageView
	  */
	public static void showNetImg(String url,Context context,ImageView imageView,final int defautDrawable){
		BitmapUtils bitmapUtils = null;
	      BitmapDisplayConfig bigPicDisplayConfig;
	        if (bitmapUtils == null) {
	           bitmapUtils = new BitmapUtils(ContactConfig.getContext());;
	        }
	        bitmapUtils.configDefaultLoadingImage(defautDrawable);
	        bitmapUtils.configDefaultLoadFailedImage(defautDrawable);

	        bigPicDisplayConfig = new BitmapDisplayConfig();
	        //bigPicDisplayConfig.setShowOriginal(true); // 显示原始图片,不压缩, 尽量不要使用, 图片太大时容易OOM。
	        bigPicDisplayConfig.setBitmapConfig(Bitmap.Config.RGB_565);
	        bigPicDisplayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(context));

	        BitmapLoadCallBack<ImageView> callback = new DefaultBitmapLoadCallBack<ImageView>() {
	            @Override
	            public void onLoadStarted(ImageView container, String uri, BitmapDisplayConfig config) {
	                super.onLoadStarted(container, uri, config);
	                //Toast.makeText(getApplicationContext(), uri, 300).show();
	              //  container.setImageResource(defautDrawable);
	            }

	            @Override
	            public void onLoadCompleted(ImageView container, String uri, Bitmap bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) {
	                super.onLoadCompleted(container, uri, bitmap, config, from);
	               // Toast.makeText(getApplicationContext(), bitmap.getWidth() + "*" + bitmap.getHeight(), 300).show();
	                if(bitmap!=null){
	         		   bitmap=  StringUtil.toRoundCorner(bitmap, 20);
	         		  container.setImageBitmap(bitmap);
	         	   }
	            }
	        };

	        bitmapUtils.display(imageView, url, bigPicDisplayConfig, callback);
	}
	// /**
	// * 显示群组网络图片
	// * @param url
	// * @param context
	// * @param imageView
	// */
	// public static void showGroupNetImg(String url,Context context,ImageView
	// imageView,final int defautDrawable,final int angle){
	//
	// BitmapDisplayConfig bigPicDisplayConfig;
	// if (bitmapUtils == null) {
	// bitmapUtils = BitmapHelp.getBitmapUtils(context.getApplicationContext());
	// }
	// bitmapUtils.configDefaultLoadingImage(defautDrawable);
	// bitmapUtils.configDefaultLoadFailedImage(defautDrawable);
	//
	// bigPicDisplayConfig = new BitmapDisplayConfig();
	// //bigPicDisplayConfig.setShowOriginal(true); // 显示原始图片,不压缩, 尽量不要使用,
	// 图片太大时容易OOM。
	// bigPicDisplayConfig.setBitmapConfig(Bitmap.Config.RGB_565);
	// bigPicDisplayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(context));
	//
	// BitmapLoadCallBack<ImageView> callback = new
	// DefaultBitmapLoadCallBack<ImageView>() {
	// @Override
	// public void onLoadStarted(ImageView container, String uri,
	// BitmapDisplayConfig config) {
	// super.onLoadStarted(container, uri, config);
	// //Toast.makeText(getApplicationContext(), uri, 300).show();
	// // container.setImageResource(defautDrawable);
	// }
	//
	// @Override
	// public void onLoadCompleted(ImageView container, String uri, Bitmap
	// bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) {
	// super.onLoadCompleted(container, uri, bitmap, config, from);
	// // Toast.makeText(getApplicationContext(), bitmap.getWidth() + "*" +
	// bitmap.getHeight(), 300).show();
	// if(bitmap!=null){
	// bitmap= StringUtil.toRoundCorner(bitmap, angle);
	// container.setImageBitmap(bitmap);
	// }
	// }
	// };
	//
	// bitmapUtils.display(imageView, url, bigPicDisplayConfig, callback);
	// }

	/**
	 * 将图片转换成base64字符串
	 * 
	 * @param imgFilePath
	 * @return
	 */
	public static String ImageToBase64Str(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		/*
		 * // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder();
		 * 
		 * return encoder.encode(data);// 返回Base64编码过的字节数组字符串
		 */
		if (data != null) {
			//return Base64.encode(new String(data));
			return Base64.encodeToString(data, Base64.DEFAULT);
		}
		return null;
	}
}
